package com.weiyuwqj.server.service.invest.module;

import com.weiyuwqj.api.constant.ItemStatus;
import com.weiyuwqj.api.constant.Message;
import com.weiyuwqj.api.exception.CrowdException;
import com.weiyuwqj.api.exception.HfException;
//import com.weiyuwqj.api.hengfeng.model.base.HfResultBean;
import com.weiyuwqj.api.model.*;
import com.weiyuwqj.api.model.vo.RepayCollectVo;
//import com.weiyuwqj.api.hengfeng.param.vo.HfBidRepayVo;
import com.weiyuwqj.api.util.IpUtils;
import com.weiyuwqj.api.util.StringUtils;
import com.weiyuwqj.server.mapper.*;
//import com.weiyuwqj.server.pay.InvestApi;
import com.weiyuwqj.server.service.account.module.DealAction;
import com.weiyuwqj.server.service.account.module.DealModule;
import com.weiyuwqj.server.service.account.module.action.user.invest.ReceiveRepayCashDealAction;
import com.weiyuwqj.server.service.account.module.action.user.invest.RepayDealAction;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by huzj on 2017/3/30.
 */
@Component
public class AssetPackageRepayModule {

    @Autowired
    BusAssetRepayMapper assetRepayMapper;

    @Autowired
    BusAssetPackagePlanMapper assetPackagePlanMapper;

    @Autowired
    BusAccountMapper accountMapper;

    @Autowired
    BusAssetCollectMapper collectMapper;

    @Autowired
    BusAssetInvestMapper assetInvestMapper;

    @Autowired
    BasItemMapper itemMapper;

    @Autowired
    BusIncomeMapper incomeMapper;

    @Autowired
    BusIncomeStatMapper incomeStatMapper;

    @Autowired
    DealModule dealModule;

    @Autowired
    BusVerifyLogMapper verifyLogMapper;

    @Autowired
    SysAssetDepositMapper sysAssetDepositMapper;

    @Autowired
    SysAssetProductMapper assetProductMapper;

    @Autowired
    BusRepayOrderMapper repayOrderMapper;

    @Autowired
    BasUserMapper userMapper;

//    @Autowired
//    InvestApi investApi;

//    //借款人还款
//    public Map brrowerPackageRepay(BusAssetRepay assetRepay) {
//
//        //判断还款计划状态
//        BasItem item = itemMapper.selectByPrimaryKey(assetRepay.getItemId());
//        BasUser user=userMapper.selectByPrimaryKey(item.getItemUserId());
//        BusAssetRepay repay = assetRepayMapper.selectByPrimaryKey(assetRepay.getId());
//        if (repay == null) {
//            throw new CrowdException("item.repay.not_found");
//        } else if (repay.getStatus() != 0) {
//            throw new CrowdException("item.repay.status_not_correct");
//        }
//
//        repay.setActualRepayAmount(repay.getRepayAmount());
//        repay.setActualRepayPrincipal(repay.getRepayPrincipal());
//        repay.setActualRepayInterest(repay.getRepayInterest());
//        repay.setStatus(1);
//        repay.setActualRepayTime(new Date());
//        repay.setPlatformId(user.getPlatformId());
//        repay.setOrderNo(item.getItemNumber());
//        //检查账户情况
//        BusAccount account = accountMapper.getBusAccountByUserId(item.getItemUserId());
//        BigDecimal repayAmount = repay.getRepayAmount();
//        if (account.getUsable().compareTo(repayAmount) == -1) {
//            throw new CrowdException("item.repay.balance_is_not_enough");
//        }
//
//        //更新标账户余额
//        int count = itemMapper.updateUsableById(item.getUsable(),repay.getActualRepayAmount(),assetRepay.getItemId());
//        if(count < 1){
//            throw new CrowdException("update_error");
//        }
//
//        //处理借款人账户
//        DealAction repayAction = new RepayDealAction();
//        repayAction.deal(item.getItemUserId(), repay.getActualRepayAmount(), "支付" + item.getItemName() + "项目本息");
//        count = dealModule.dealAction(repayAction);
//        if (count < 1) {
//            throw new CrowdException("update_error");
//        }
//
//        //更新标的状态
//        if(repay.getRepayCurrentPeriod() == 1){
//            itemMapper.updateItemStatus(ItemStatus.REPAYING, ItemStatus.REPAY_COMPLETE, repay.getItemId());
//        }else if (repay.getRepayCurrentPeriod().intValue() == repay.getRepayTotalPeriod().intValue()) {
//            itemMapper.updateItemStatus(ItemStatus.REPAY_PART, ItemStatus.REPAY_COMPLETE, repay.getItemId());
//        } else {
//            itemMapper.updateItemStatus(ItemStatus.REPAYING, ItemStatus.REPAY_PART, repay.getItemId());
//        }
//
//        //更新repay
//        count = assetRepayMapper.updateRepayStatus(repay);
//        if(count < 1){
//            throw new CrowdException("update_error");
//        }
//
//        //添加日志，还款的类型5
//        BusVerifyLog log = new BusVerifyLog();
//        log.setOperateUserId(1);
//        log.setContent("借款人项目还款：" + item.getItemName());
//        log.setAddtime(new Date());
//        log.setType((byte) 5);
//        log.setItemId(repay.getItemId());
//        log.setStatus((byte) 1);
//        log.setAddip(IpUtils.get());
//        verifyLogMapper.insert(log);
//
//        List<BusAssetRepay> itemRepays = new ArrayList();
//        itemRepays.add(repay);
//
//	    HfResultBean result = investApi.borrowRepay(itemRepays);
//	    if (result.isSuccess()) {
//		    return Message.OK;
//        }else {
//		    throw new HfException("HfException", result.getMessageText());
//	    }
//    }

//    //标账户还款给投资人
//    public Map packageRepay(Integer packagePlanId,BusAssetRepay assetRepay,BusAssetPackagePlan packagePlan) {
//
//        //判断还款计划状态
//        BasItem item = itemMapper.selectByPrimaryKey(assetRepay.getItemId());
//        if (assetRepay == null) {
//            throw new CrowdException("item.repay.not_found");
//        } else if (assetRepay.getStatus() != 1) {
//            throw new CrowdException("item.repay.status_not_correct");
//        }
//
//        //检查标的账户金额
//        BigDecimal repayAmount = assetRepay.getActualRepayAmount();
//        if (item.getUsable().compareTo(repayAmount) == -1) {
//            throw new CrowdException("item.repay.balance_is_not_enough");
//        }
//
//        //查询项目待收计划和债权待收计划
//        List<RepayCollectVo> assetCollectList = collectMapper.listByPlanIdAndCurrentPeriod(packagePlanId, packagePlan.getPeriods(),assetRepay.getItemId());
//
//        BigDecimal totalCollectAmount = BigDecimal.ZERO;
//        BigDecimal totalCollectPrincipal = BigDecimal.ZERO;
//        BigDecimal totalCollectInterest = BigDecimal.ZERO;
//        int count;
//        for (RepayCollectVo repayCollectVo : assetCollectList) {
//
//            //处理投资人待收
//            Map map = new HashMap();
//            map.put("collectAmount", repayCollectVo.getCollectAmount());
//            map.put("collectPrincipal", repayCollectVo.getCollectPrincipal());
//            map.put("collectInterest", repayCollectVo.getCollectInterest());
//            map.put("collectTime", new Date());
//            map.put("collectStatus", 1);
//            map.put("id", repayCollectVo.getId());
//            map.put("userId", repayCollectVo.getInvestUserId());
//            collectMapper.updateActualCollect(map);
//
//            repayCollectVo.setActualCollectAmount(repayCollectVo.getCollectAmount());
//            repayCollectVo.setActualCollectPrincipal(repayCollectVo.getActualCollectPrincipal());
//            repayCollectVo.setActualCollectInterest(repayCollectVo.getActualCollectInterest());
//            repayCollectVo.setActualCollectTime(new Date());
//
//            //统计还款总额
//            totalCollectAmount = totalCollectAmount.add(repayCollectVo.getCollectAmount().
//                    subtract(repayCollectVo.getAdditionalRateAmount()));
//            totalCollectPrincipal = totalCollectPrincipal.add(repayCollectVo.getCollectPrincipal());
//            totalCollectInterest = totalCollectInterest.add(repayCollectVo.getCollectInterest().
//                    subtract(repayCollectVo.getAdditionalRateAmount()));
//
//            //更新invest表
//            if (repayCollectVo.getCollectTotalPeriod().intValue() == repayCollectVo.getCollectCurrentPeriod().intValue()) {
//                assetInvestMapper.updateItemInvestStatus(1, 3, repayCollectVo.getInvestId());
//            }
//
//            //更新投资表
//            assetInvestMapper.updateItemRepayInvestCollet(repayCollectVo.getCollectPrincipal(),
//                    repayCollectVo.getCollectInterest(),
//                    repayCollectVo.getInvestId());
//
//            //向income中插入一条数据
//            BusIncome busIncome = new BusIncome();
//            busIncome.setIncomeAmout(repayCollectVo.getActualCollectInterest());
//            busIncome.setUserId(repayCollectVo.getInvestUserId());
//            busIncome.setIncomeType(2);
//            Date date = new Date();
//            busIncome.setAddtime(date);
//            SimpleDateFormat incomeDate = new SimpleDateFormat("yyyyMMdd");
//            busIncome.setIncomeDate(incomeDate.format(date));
//            incomeMapper.insert(busIncome);
//
//            //向income_stat表中修改待收和已收收益
//            Map<String, Object> param = new HashMap<String, Object>();
//            param.put("userId", repayCollectVo.getInvestUserId());
//            param.put("waitIncome", BigDecimal.ZERO.subtract(repayCollectVo.getActualCollectInterest()));
//            param.put("earnedIncome", repayCollectVo.getActualCollectInterest());
//            param.put("totalIncome", 0);
//            count = incomeStatMapper.updateByWaitEarned(param);
//            if (count < 1) {
//                throw new CrowdException("update_error");
//            }
//
//            //处理投资人账户金额
//            DealAction receiveRepayAction = new ReceiveRepayCashDealAction();
//            receiveRepayAction.deal(repayCollectVo.getInvestUserId(),
//                    repayCollectVo.getCollectAmount().subtract(repayCollectVo.getAdditionalRateAmount()),
//                    item.getItemName() + "项目回款本息");
//            count = dealModule.dealAction(receiveRepayAction);
//            if (count < 1) {
//                throw new CrowdException("update_error");
//            }
//        }
//
//        boolean isPayoff = false;
//        if (assetRepay.getRepayCurrentPeriod().intValue() == assetRepay.getRepayTotalPeriod().intValue()) {
//            isPayoff = !isPayoff;
//        }
//
//        //更新还款状态
//        Map param = new HashMap();
//        param.put("newStatus",2);
//        param.put("oldStatus",1);
//        param.put("id",assetRepay.getId());
//        assetRepayMapper.updateRepayByStatusAndId(param);
//
//        //插入还款订单表
//        String orderNo = StringUtils.getOrderNo();
//        BusRepayOrder repayOrder = new BusRepayOrder();
//        repayOrder.setAddip(IpUtils.get());
//        repayOrder.setAddtime(new Date());
//        repayOrder.setRepayAmount(assetRepay.getRepayAmount());
//        repayOrder.setRepayId(assetRepay.getId());
//        repayOrder.setRepayOrder(orderNo);
//        repayOrder.setRepayType(2);
//        repayOrder.setItemId(assetRepay.getItemId());
//        repayOrder.setRepayPeriod(packagePlan.getPeriods());
//        repayOrderMapper.insert(repayOrder);
//
//        //请求恒丰
//        HfBidRepayVo repayVo = new HfBidRepayVo();
//        repayVo.setBidId(item.getId() + "");
//        repayVo.setTotalAmount(repayAmount);
//        repayVo.setTotalNum(assetCollectList.size());
//        repayVo.setOrderId(assetRepay.getOrderNo());
//        repayVo.setRepayStatus(5);
//        repayVo.setPayoff(isPayoff);
//	    HfResultBean result = investApi.bidRepay(repayVo, assetCollectList);// 请求恒丰
//	    return Message.OK;
//    }



    /*public Map packageRepay(Integer packagePlanId,BusAssetRepay assetRepay,BusAssetPackagePlan packagePlan) {

            //还款人应还的金额
            BigDecimal collectAmount = BigDecimal.ZERO;
            BigDecimal collectPrincipal = BigDecimal.ZERO;
            BigDecimal collectInterest= BigDecimal.ZERO;

            BasItem item = itemMapper.selectByPrimaryKey(assetRepay.getItemId());

            List<RepayCollectVo> assetCollectList = collectMapper.listByPlanIdAndCurrentPeriod(packagePlanId, packagePlan.getPeriods());
            for (RepayCollectVo assetCollect : assetCollectList){
                //处理投资人待收
//                assetCollect.setActualCollectAmount(assetCollect.getCollectAmount());
//                assetCollect.setActualCollectPrincipal(assetCollect.getCollectPrincipal());
//                assetCollect.setActualCollectInterest(assetCollect.getCollectInterest());
//                assetCollect.setActualCollectTime(new Date());
//                assetCollect.setCollectStatus(1);
//                collectMapper.updateByPrimaryKey(assetCollect);

                //处理借款人账户金额
                collectAmount = collectAmount.add(assetCollect.getActualCollectAmount().subtract(assetCollect.getAdditionalRateAmount()));
                collectPrincipal = collectPrincipal.add(assetCollect.getActualCollectPrincipal());
                collectInterest = collectInterest.add(assetCollect.getActualCollectInterest().subtract(assetCollect.getAdditionalRateAmount()));

                if (assetCollect.getCollectTotalPeriod() == assetCollect.getCollectCurrentPeriod()) {
                    assetInvestMapper.updateItemInvestStatus(1, 3, assetCollect.getInvestId());
                }
                assetInvestMapper.updateItemRepayInvestCollet(assetCollect.getCollectPrincipal(),
                        assetCollect.getCollectInterest(),
                        assetCollect.getInvestId());

                //向income中插入一条数据
                BusIncome busIncome = new BusIncome();
                busIncome.setIncomeAmout(assetCollect.getCollectInterest());
                busIncome.setUserId(assetCollect.getInvestUserId());
                busIncome.setIncomeType(2);
                Date date = new Date();
                busIncome.setAddtime(date);
                SimpleDateFormat incomeDate = new SimpleDateFormat("yyyyMMdd");
                busIncome.setIncomeDate(incomeDate.format(date));
                incomeMapper.insert(busIncome);
                //向income_stat表中修改待收和已收收益
                Map<String, Object> param = new HashMap<String, Object>();
                param.put("userId", assetCollect.getInvestUserId());
                param.put("waitIncome", BigDecimal.ZERO.subtract(assetCollect.getCollectInterest()));
                param.put("earnedIncome", assetCollect.getCollectInterest());
                param.put("totalIncome", 0);
                incomeStatMapper.updateByWaitEarned(param);

                //处理投资人账户金额
                DealAction receiveRepayAction = new ReceiveRepayCashDealAction();
                receiveRepayAction.deal(assetCollect.getInvestUserId(),
                        assetCollect.getActualCollectAmount().subtract(assetCollect.getAdditionalRateAmount()),
                        packagePlan.getPackagePlanName() + "回款本息");
                dealModule.dealAction(receiveRepayAction);
            }

            //更新标的状态
            if (assetRepay.getRepayTotalPeriod() == assetRepay.getRepayCurrentPeriod()) {
                itemMapper.updateItemStatus(ItemStatus.REPAY_PART, ItemStatus.REPAY_COMPLETE, assetRepay.getItemId());

                //更新借款额度
                final HashMap<String,Object> map = new HashMap<String, Object>();
                final SysAssetProductVo productVo= assetProductMapper.findByItemId(item.getId());
                if(productVo != null){
                    map.put("companyId", productVo.getCompanyId());
                }
                map.put("amount",item.getItemAccount());
                int count = sysAssetDepositMapper.updateByAmount(map);
                if(count < 1){
                    throw new CrowdException("update_error");
                }
            } else {
                itemMapper.updateItemStatus(ItemStatus.REPAYING, ItemStatus.REPAY_PART, assetRepay.getItemId());
            }

            BusAssetRepay repay = assetRepayMapper.selectByPrimaryKey(assetRepay.getId());
            repay.setStatus(1); //已经回款
            repay.setActualRepayTime(new Date());
            repay.setActualRepayAmount(collectAmount);
            repay.setActualRepayInterest(collectPrincipal);
            repay.setActualRepayPrincipal(collectInterest);
            int repayCount = assetRepayMapper.updateRepayStatus(repay);
            if (repayCount < 1) {
                throw new CrowdException("item.repay.statusNotEqualOne");
            }
            //添加日志，还款的类型5
            BusVerifyLog log = new BusVerifyLog();
            log.setOperateUserId(1);
            log.setContent("项目还款：" + packagePlan.getPackagePlanName());
            log.setAddtime(new Date());
            log.setType((byte) 5);
            log.setItemId(assetRepay.getItemId());
            log.setStatus((byte) 1);
            log.setAddip(IpUtils.get());
            verifyLogMapper.insert(log);

        return Message.OK;
    }*/

}
